import pino from 'pino';
import path from 'path';
import fs from 'fs';
import { config } from '@/config';

// 确保日志目录存在
const logDir = path.dirname(config.log.filePath);
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

/**
 * 简单的控制台日志器（用于开发环境）
 */
class SimpleLogger {
  constructor(_level: string = 'info') {
    // level 参数目前不用，但保留接口兼容性
  }

  private formatMessage(level: string, message: string, data?: any): string {
    const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const levelUpper = level.toUpperCase().padEnd(5);
    let output = `[${timestamp}] ${levelUpper}: ${message}`;
    
    if (data && typeof data === 'object') {
      output += ' ' + JSON.stringify(data, null, 2);
    }
    
    return output;
  }

  info(data: any, message?: string): void {
    const msg = message || (typeof data === 'string' ? data : '');
    const logData = typeof data === 'object' ? data : undefined;
    console.log(this.formatMessage('INFO', msg, logData));
  }

  error(data: any, message?: string): void {
    const msg = message || (typeof data === 'string' ? data : '');
    const logData = typeof data === 'object' ? data : undefined;
    console.error(this.formatMessage('ERROR', msg, logData));
  }

  warn(data: any, message?: string): void {
    const msg = message || (typeof data === 'string' ? data : '');
    const logData = typeof data === 'object' ? data : undefined;
    console.warn(this.formatMessage('WARN', msg, logData));
  }

  debug(data: any, message?: string): void {
    const msg = message || (typeof data === 'string' ? data : '');
    const logData = typeof data === 'object' ? data : undefined;
    console.debug(this.formatMessage('DEBUG', msg, logData));
  }

  fatal(data: any, message?: string): void {
    const msg = message || (typeof data === 'string' ? data : '');
    const logData = typeof data === 'object' ? data : undefined;
    console.error(this.formatMessage('FATAL', msg, logData));
  }
}

/**
 * 创建 Pino 日志实例
 */
const createLogger = () => {
  const isDevelopment = config.app.env === 'development';
  
  // 在开发环境中使用简单日志器，避免中文乱码问题
  if (isDevelopment && process.platform === 'win32') {
    return new SimpleLogger(config.log.level) as any;
  }
  
  // 设置控制台编码（Windows 支持）
  if (process.platform === 'win32' && process.stdout.isTTY) {
    process.stdout.setEncoding('utf8');
    process.stderr.setEncoding('utf8');
  }
  
  const baseConfig = {
    level: config.log.level,
    timestamp: pino.stdTimeFunctions.isoTime,
    formatters: {
      level: (label: string) => ({ level: label }),
    },
  };

  // 开发环境使用简化的配置，避免 Worker 线程问题
  if (isDevelopment) {
    return pino({
      ...baseConfig,
      // 使用基本的 JSON 输出，避免 pretty-print 的问题
      serializers: {
        // 确保中文字符正确显示
        msg: (msg: string) => msg,
      },
    });
  }

  // 生产环境输出到文件
  return pino(
    baseConfig,
    pino.destination({
      dest: config.log.filePath,
      sync: false,
    })
  );
};

export const logger = createLogger();

/**
 * 请求日志中间件使用的日志实例
 */
export const httpLogger = config.app.env === 'development' && process.platform === 'win32' 
  ? new SimpleLogger(config.log.level) as any
  : pino({
      level: config.log.level,
      // 使用基本配置，避免 transport 问题
    });

export default logger;